package com.junan.galiao.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;

/**
 * @author junan
 * @version V1.0
 * @className DateFormatSerializer
 * @disc
 * @date 2019/11/30 22:09
 */
public class TimestampFormatSerializer extends JsonSerializer<Timestamp> {

    private static SimpleDateFormat simpleDateFormat = null;

    @Override
    public void serialize(Timestamp timestamp, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        String format = getDateFormat().format(timestamp);
        jsonGenerator.writeString(format);
    }

    public static SimpleDateFormat getDateFormat() {
        if(simpleDateFormat == null) {
            synchronized (TimestampFormatSerializer.class) {
                if(simpleDateFormat == null) {
                    simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                }
            }
        }
        return simpleDateFormat;
    }
}